const express = require('express');
var bodyParser = require('body-parser');
const request = require('request')
const path = require('path')
const app = express();
const port = 80;

// 微信开发平台，app应用账号 
// 此处最妙的地方，因为我们没有【微信开放平台】的账号，这个账号是公司才能注册的，因此这里是借用了txjava.com公司的账号实现的功能
/**
 * 参考视频：https://www.bilibili.com/video/BV1RJ411N7ne?spm_id_from=333.1007.top_right_bar_window_custom_collection.content.click
 * 参考文章1：https://baijiahao.baidu.com/s?id=1716997401492524511&wfr=spider&for=pc
 * 官方文档2：https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
 * 
 * 或许你有许多疑问，不懂的随时问我，微信号yizheng369
 */
let wxkfObj={
  APPID: "wx7287a60bb700fd21",
  secret: "1ef8755f92bebae8ad7bab432ba29cbf",
  REDIRECT_URI: 'http://www.txjava.cn/loginServlet'
}

// 有效期
var enableTimestamp = 0;
// 过渡时间 提早5分钟，重新获取token
var transitionTime = 5 * 60 * 1000;

// 处理跨域
//设置跨域访问
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  next();
})

app.get('/',(req,res)=>{
  console.log('有人来：',Date.now());
  res.send("hello world!")
})

// 处理静态资源访问
app.use('/html',express.static('html'));

function requestGetFun(url){
  console.log('url',url);
  return new Promise((resolve,reject) => {
    request(url, function (error, response, body) {
      if(!error){
        console.log('成功2：error, response, body',body)
        resolve(body)
      }else{
        console.log('error：',error)
        reject(error)
      }
    });
    
  })
}


app.get('/loginServlet',async (req,res)=>{
  console.log('微信回调：',req.query);
  let userObj={};
  // let code_url = `https://open.weixin.qq.com/connect/qrconnect?
  // appid=${wxkfObj.APPID}&redirect_uri=${wxkfObj.REDIRECT_URI}&response_type=code&scope=SCOPE&state=STATE#wechat_redirect`
  // let rel = await requestGetFun(code_url)
  // console.log('codeRel:',rel);

  if(req.query.code){
    let token_url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${wxkfObj.APPID}&secret=${wxkfObj.secret}&code=${req.query.code}&grant_type=authorization_code`
    let rel = await requestGetFun(token_url)
    console.log('有token:',typeof rel);
    if(rel){
      rel = JSON.parse(rel)
    }
    console.log('有openid:',rel);
    if(rel.access_token && rel.openid){
      let user_url = `https://api.weixin.qq.com/sns/userinfo?access_token=${rel.access_token}&openid=${rel.openid}`
      let user = await requestGetFun(user_url)
      userObj = JSON.parse(user)
      console.log('最后：',userObj);
    }
  }else{
    console.log('用户不授权1---');
  }
  let {nickname,headimgurl} = userObj;
  res.header("Content-Type", "text/html; charset=utf-8")
  res.redirect(`/html?nickname=${nickname}&headimgurl=${headimgurl}`)
})




// 解析 application/json
app.use(bodyParser.json()); 
// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());

app.listen(port,()=>{
  console.log('server open at: http://localhost:'+port);
})

